<template>
  <a-drawer height="85%" placement="bottom" v-model:visible="visible" :title="title" @before-ok="onOk">
    <a-row justify="center">
      <a-col :span="12" style="min-width: 400px">
        <a-form ref="formRef" :model="form" size="medium" auto-label-width>
          <a-form-item field="categoryId" label="所属分类">
            <a-cascader :options="cateList" v-model="form.categoryId" placeholder="请选择分类" />
          </a-form-item>
          <a-form-item field="sourceType" label="所属平台">
            <a-select v-model="form.sourceType" placeholder="选择所属平台">
              <a-option v-for="item in platformList" :key="item.id" :value="item.id" :label="item.title"></a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="商品" field="goods">
            <GiTable
              row-key="id"
              v-model:columns="columns"
              :data="form.goods"
              :scroll="{ x: '100%', y: false, minWidth: 400 }"
              :pagination="false"
              :simple="true"
            >
              <template #custom-extra>
                <a-space>
                  <a-input v-model="params.goodsId" placeholder="输入商品ID"></a-input>
                  <a-input v-model="params.activityId" placeholder="输入商品券ID"></a-input>
                  <a-button type="primary" size="small" @click="getGoods" :loading="loading">
                    <template #icon>
                      <icon-plus />
                    </template>
                    <template #default>获取商品</template>
                  </a-button>
                </a-space>
              </template>
              <template #ID="{ record }">
                <ms-copy-div title="商品ID" :text="record.goodsId" show-left-title></ms-copy-div>
                <ms-copy-div title="券ID" :text="record.activityId" show-left-title></ms-copy-div>
              </template>
              <template #action="{ rowIndex }">
                <a-button type="text" size="small" @click="form.goods.splice(rowIndex, 1)"> 删除 </a-button>
              </template>
            </GiTable>
          </a-form-item>
          <a-form-item label="推荐商品图片">
            <MsUpload
              :limit="5"
              v-model="fileList"
              placeholder="图片尺寸：264*190px，大小：2Mb以内，格式：jpg/png"
            ></MsUpload>
          </a-form-item>
          <a-form-item field="content" label="文案信息">
            <a-textarea
              :auto-size="{
                minRows: 6,
                maxRows: 10
              }"
              v-model="form.content"
            />
          </a-form-item>
          <!-- <a-form-item label="视频" field="videoLink">
            <MsUpload type="video" v-model="form.videoLink"></MsUpload>
          </a-form-item>
          <a-form-item label="视频封面" field="videoUrl">
            <MsUpload v-model="form.videoUrl"></MsUpload>
          </a-form-item> -->
          <a-form-item field="buyerCircleAuthorId" label="发布者">
            <a-cascader :options="authorList" v-model="form.buyerCircleAuthorId" placeholder="请选择分类" />
          </a-form-item>
          <a-form-item label="分享量" field="shareNum">
            <a-input-number :min="0" v-model="form.shareNum" placeholder="请输入分享量" />
          </a-form-item>
          <a-form-item label="发布时间" field="publishedAt">
            <a-date-picker show-time v-model="form.publishedAt" />
          </a-form-item>
          <a-form-item label="排序" field="title">
            <a-input-number :min="1" v-model="form.position" placeholder="请输入排序" />
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
  </a-drawer>
</template>

<script setup>
import { buyerCirclePreferredAdd, buyerCirclePreferredEdit, goodsDetails, buyerCirclePreferredDetail } from '@/apis'
import { Message } from '@arco-design/web-vue'
import { reAssign } from '@/utils/common'
import ImgHoverPreview from '@/components/ImgHoverPreview/index.vue'

defineProps({
  cateList: Array,
  platformList: Array,
  authorList: Array
})
const emit = defineEmits(['getTableData'])

const title = computed(() => (form.id ? '编辑买手爆款' : '新增买手爆款'))
const visible = ref(false)
const formRef = ref()
const loading = ref(false)
const fileList = ref()

const params = reactive({
  goodsId: undefined,
  activityId: undefined
})

const form = reactive({
  id: undefined,
  categoryId: undefined,
  sourceType: undefined,
  buyerCircleAuthorId: undefined,
  shareNum: undefined,
  publishedAt: undefined,
  content: undefined,
  fileList: undefined,
  goods: undefined,
  position: 1,
  pid: 10
})

const columns = ref([
  {
    title: '商品名称',
    width: 200,
    dataIndex: 'title'
  },
  {
    title: '商品图',
    width: 90,
    render: (data) => {
      const url = data.record.picUrl
      return h(ImgHoverPreview, { url, width: 50 })
    }
  },
  {
    title: '商品ID',
    width: 250,
    slotName: 'ID'
  },
  {
    title: '券后价',
    width: 100,
    dataIndex: 'actualPrice'
  },
  {
    title: '操作',
    width: 90,
    fixed: 'right',
    align: 'center',
    slotName: 'action'
  }
])

// 打开编辑框并回显表单值
const addOrEdit = async (id) => {
  visible.value = true
  let item = false
  if (id) {
    const res = await buyerCirclePreferredDetail({ id })
    item = res.data
  }
  reAssign(form, item)
  fileList.value =
    item && item.fileList
      ? item.fileList
          .map((item) => {
            return item.url
          })
          .join(',')
      : undefined
  form.position = item ? item.position : 1
  form.goods = item ? item.goods : []
  item && formRef.value?.validate()
}

// 点击确认添加/编辑
const onOk = async () => {
  const validateResult = await formRef.value?.validate()
  if (validateResult) return false
  const api = form.id ? buyerCirclePreferredEdit : buyerCirclePreferredAdd
  await api({
    ...form,
    fileList: fileList.value.split(','),
    goods: form.goods.length > 0 ? JSON.stringify(form.goods) : undefined
  })
  Message.success('操作成功')
  emit('getTableData')
  return true
}

const getGoods = async () => {
  try {
    if (!form.sourceType) return Message.warning('请先选择平台')
    loading.value = true
    const res = await goodsDetails({ ...params, sourceType: form.sourceType })
    form.goods.push(res.data)
    params.goodsId = params.activityId = undefined
  } finally {
    loading.value = false
  }
}

provide('formRef', formRef)
defineExpose({ addOrEdit })
</script>
